<template>
  <a-form class="smart-query-form">
    <a-row class="smart-query-form-row">

      <a-form-item class="smart-query-form-item" label="所属品类">
        <a-select v-model:value="queryForm.category" allowClear placeholder="选择品类" style="width: 160px">
          <a-select-option value="1">手机</a-select-option>
          <a-select-option value="2">平板</a-select-option>
        </a-select>
      </a-form-item>

      <a-form-item class="smart-query-form-item" label="所属品牌">
        <a-select v-model:value="queryForm.brandId" allowClear placeholder="选择品牌" style="width: 160px">
          <a-select-option v-for="option in brandOptions" :value="option.id">{{ option.brandName }}</a-select-option>
        </a-select>
      </a-form-item>

      <a-form-item class="smart-query-form-item" label="型号名称">
        <a-input v-model:value="queryForm.modelName" placeholder="请输入型号名称" style="width: 160px"/>
      </a-form-item>

      <a-form-item class="smart-query-form-item" label="更新时间">
        <a-space :size="12" direction="vertical">
          <a-range-picker v-model:value="searchDate" :ranges="defaultTimeRanges" @change="dateChange"/>
        </a-space>
      </a-form-item>

      <a-form-item class="smart-query-form-item smart-margin-left10">
        <a-button type="primary" @click="resetPageNumAjaxQuery">
          <template #icon>
            <SearchOutlined/>
          </template>
          查询
        </a-button>
        <a-button @click="resetQuery">
          <template #icon>
            <ReloadOutlined/>
          </template>
          重置
        </a-button>
      </a-form-item>
    </a-row>
  </a-form>

  <a-card :bordered="false" :hoverable="true" size="small">
    <a-row class="smart-table-btn-block">
      <div class="smart-table-operate-block">
        <a-button size="small" type="primary" @click="add()">
          <template #icon>
            <PlusOutlined/>
          </template>
          新增估价配置
        </a-button>
      </div>
    </a-row>

    <a-table
        :columns="columns"
        :dataSource="tableData"
        :loading="tableLoading"
        :pagination="false"
        :scroll="{ x: 1800 }"
        bordered
        rowKey="id"
        size="small"
    >
      <template #bodyCell="{ column, record, text }">
        <template v-if="column.dataIndex === 'icon'">
          <a-image
              :src="text"
              :width="80"
          />
        </template>
        <template v-if="column.dataIndex === 'category'">
          {{ text === 1 ? '手机' : text === 2 ? '平板' : '未知' }}
        </template>
        <template v-if="column.dataIndex === 'status'">
          <span :style="{color: text===1?'#87d068':'#f50'}">
          {{ text === 1 ? '上架' : text === 0 ? '下架' : '未知' }}
          </span>
        </template>

        <template v-if="column.dataIndex === 'operate'">
          <div class="smart-table-operate">
            <a-button type="link" @click="showEvaluateModal(record)">估价</a-button>
            <a-button type="link" @click="copy(record)">复制</a-button>
            <a-button type="link" @click="update(record)">编辑</a-button>
            <a-button :style="{color: record.status===0?'#87d068':'#f50'}" type="link" @click="upOrDown(record)">
              {{ record.status === 0 ? '上架' : '下架' }}
            </a-button>
            <a-button danger type="link" @click="confirmDelete(record)">删除</a-button>
          </div>
        </template>
      </template>
    </a-table>

    <div class="smart-query-table-page">
      <a-pagination
          v-model:current="queryForm.pageNum"
          v-model:pageSize="queryForm.pageSize"
          :defaultPageSize="queryForm.pageSize"
          :pageSizeOptions="PAGE_SIZE_OPTIONS"
          :show-total="(total) => `共${total}条`"
          :total="total"
          show-less-items
          showQuickJumper
          showSizeChanger
          @change="ajaxQuery"
          @showSizeChange="ajaxQuery"
      />
    </div>
  </a-card>
  <!--  添加和修改对话框-->
  <a-modal :title="`${formData.id?'编辑':'新增'}品牌`" :visible="modalVisible" @cancel="onClose" @ok="handleOk">

    <a-form ref="formRef" :label-col="labelCol" :model="formData" :rules="rules" :wrapper-col="wrapperCol">
      <a-form-item label="品牌名称" name="brandName">
        <a-input v-model:value="formData.brandName" placeholder="请输入品牌名称"/>
      </a-form-item>
      <a-form-item label="图片">
        <FileUpload
            :defaultFileList="defaultImgList.arr"
            :folder="FILE_FOLDER_TYPE_ENUM.COMMON.value"
            :maxUploadSize="1"
            :multiple="true"
            buttonText="点击上传图片"
            list-type="picture-card"
            @change="imgChange"
        />
      </a-form-item>
    </a-form>
  </a-modal>
  <EvaluateModal ref="evaluateModalRef"></EvaluateModal>
</template>


<script setup>
import {defaultTimeRanges} from "/@/lib/default-time-ranges";
import {PAGE_SIZE, PAGE_SIZE_OPTIONS} from "/@/constants/common-const";
import {nextTick, onMounted, reactive, ref} from "vue";
import {smartSentry} from "/@/lib/smart-sentry";
import {TABLE_ID_CONST} from "/@/constants/support/table-id-const";
import TableOperator from "/@/components/support/table-operator/index.vue";
import {modelEvaluateApi} from './model-evaluate';
import {message, Modal} from "ant-design-vue";
import {SmartLoading} from '/@/components/framework/smart-loading';
import _ from 'lodash';
import {FILE_FOLDER_TYPE_ENUM} from "/@/constants/support/file-const";
import FileUpload from "/@/components/support/file-upload/index.vue";
import {brandApi} from "/@/views/business/data-config/brand/brand-api";
import {useRouter} from 'vue-router';
import EvaluateModal from "/@/views/business/evaluate/model-evaluate/evaluate-model.vue"


const router = useRouter();
const evaluateModalRef = ref();

const labelCol = {style: {width: '150px'}};
const wrapperCol = {span: 14};
const rules = {
  brandName: [{required: true, message: '品牌名称不能为空'}],
};
const formDataDefault = {
  id: undefined,
  brandName: undefined, //品牌名称
  icon: undefined,
};
let defaultImgList = reactive({arr: []});
let formData = reactive({...formDataDefault});
// 组件ref
const formRef = ref();
let brandOptions = ref([]);

/*
*
bak (string, optional): 备注 ,
brandId (integer, optional): 品牌 id ,
category (integer, optional): 所属品类 1.手机 2.平板 ,
context (string, optional): 扣费模板json ,
createTime (string, optional): 创建时间 ,
id (integer, optional): id ,
modelId (integer, optional): 型号 id ,
newPrice (number, optional): 准新价 ,
optionId (string, optional): 选项id ,
problemId (string, optional): 题目id ,
questionContext (string, optional): 题目json ,
status (integer, optional): 0下架 1上架 ,
title (string, optional): 标题 ,
updateTime (string, optional): 修改时间 ,
usedPrice (number, optional): 二手价
* */
const columns = ref([
  {
    align: 'center',
    title: 'id',
    dataIndex: 'id',
    width: 80,
  },
  {
    align: 'center',
    title: '型号id',
    dataIndex: 'modelId',
    width: 80,
  },
  {
    align: 'center',
    title: '型号名称',
    dataIndex: 'modelName',
    width: 220,
  },
  {
    align: 'center',
    title: '所属品牌',
    dataIndex: 'brandName',
    width: 120,
  },
  {
    align: 'center',
    title: '所属品类',
    dataIndex: 'category',
    width: 80,
  },
  {
    align: 'center',
    title: '状态',
    dataIndex: 'status',
    width: 80,
  },
  {
    align: 'center',
    title: '更新时间',
    dataIndex: 'updateTime',
    width: 100,
  },
  {
    align: 'center',
    title: '备注',
    dataIndex: 'bak',
    width: 100,
  },
  {
    align: 'center',
    title: '操作',
    dataIndex: 'operate',
    width: 200,
    fixed: 'right'
  },
]);

const queryFormDataDefault = {
  updateTimeBegin: undefined, //修改时间 开始
  updateTimeEnd: undefined, //修改时间 结束
  category: undefined, //品类
  brandId: undefined, //品牌
  modelName: undefined, //型号名称
  pageNum: 1,
  pageSize: PAGE_SIZE,
};
const queryForm = reactive({...queryFormDataDefault});
const tableLoading = ref(false);
const tableData = ref([]);
const total = ref();
// 日期选择
let searchDate = ref();
const modalVisible = ref(false);

function dateChange(dates, dateStrings) {
  queryForm.updateTimeBegin = dateStrings[0];
  queryForm.updateTimeEnd = dateStrings[1];
}

// 重置查询条件
function resetQuery() {
  searchDate.value = [];
  Object.assign(queryForm, queryFormDataDefault);
  ajaxQuery();
}

onMounted(() => {
  ajaxQuery();
  queryBrand();
});

function resetPageNumAjaxQuery(){
  queryForm.pageNum = 1;
  ajaxQuery();
}
// 查询
async function ajaxQuery() {
  try {
    tableLoading.value = true;
    let responseModel = await modelEvaluateApi.queryPage(queryForm);
    const list = responseModel.data.list;
    total.value = responseModel.data.total;
    tableData.value = list;
  } catch (e) {
    smartSentry.captureError(e);
  } finally {
    tableLoading.value = false;
  }
}

// 查询品牌
async function queryBrand() {
  try {
    let responseModel = await brandApi.queryPage({pageNum: 1, pageSize: 200});
    brandOptions.value = responseModel.data.list;
  } catch (e) {
    smartSentry.captureError(e);
  }
}

// 图片改变
function imgChange(e) {
  console.log(e[0])
  formData.icon = e[0]?.url || '';
}

// 添加
function add() {
  router.push({path: '/model-evaluate-config', query: {pageType: 'add'}});
}

// 修改
function update(record) {
  router.push({path: '/model-evaluate-config', query: {pageType: 'edit', modelEvaluateId: record.id}});
}

// 复制
function copy(record) {
  router.push({path: '/model-evaluate-config', query: {pageType: 'copy', modelEvaluateId: record.id}});
}

// 修改
async function upOrDown(record) {
  Modal.confirm({
    title: '提示',
    content: `确定要${record.status === 0 ? '上架' : '下架'}吗？`,
    okText: '确定',
    okType: 'danger',
    onOk: async () => {
      try {
        SmartLoading.show();
        await modelEvaluateApi.upOrDown(record.id);
        message.success(`${record.status === 0 ? '上架' : '下架'}成功`);
        ajaxQuery();
      } catch (e) {
        smartSentry.captureError(e);
      } finally {
        SmartLoading.hide();
      }
    },
    cancelText: '取消',
    onCancel() {
      return Promise.resolve();
    },
  });
}

const showModal = () => {
  modalVisible.value = true;
  nextTick(() => {
    formRef.value.clearValidate();
  });
};

const handleOk = (e) => {
};

function onClose() {
  Object.assign(formData, formDataDefault);
  defaultImgList.arr = [];
  modalVisible.value = false;
}

// 删除
function confirmDelete(record) {
  Modal.confirm({
    title: '提示',
    content: '确定要删除【' + record.brandName + '】吗?',
    okText: '删除',
    okType: 'danger',
    onOk() {
      singleDelete(record);
    },
    cancelText: '取消',
    onCancel() {
      return Promise.resolve();
    },
  });
}

async function singleDelete(brandData) {
  try {
    SmartLoading.show();
    await modelEvaluateApi.delete(brandData.id);
    message.success('删除成功');
    ajaxQuery();
  } catch (e) {
    smartSentry.captureError(e);
  } finally {
    SmartLoading.hide();
  }
}

function showEvaluateModal(record) {
  evaluateModalRef.value.showModal(record);
}
</script>

<style lang="less" scoped>

</style>